package com.jy.modules.cims.common.controller;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.component.common.service.TCMmRiskFundService;
import com.jy.modules.cims.component.sysAssist.CSysAssistImpl;
import com.jy.modules.cims.data.common.dto.TCMmBailBondDTO;
import com.jy.modules.cims.data.common.dto.TCMmCooperorgDealDTO;
import com.jy.modules.cims.data.common.dto.TCMmCostdealAdOrgdealDTO;
import com.jy.modules.cims.data.common.dto.TCMmDealCostDTO;
import com.jy.modules.cims.data.common.dto.TCMmRiskFundDTO;
import com.jy.modules.cims.data.common.dto.TCMmRiskFundDealDetailDTO;
import com.jy.modules.cims.deal.service.DealService;
import com.jy.platform.core.common.BaseDTO;
import com.jy.platform.core.message.DataMsg;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.PageUtil;
import com.jy.platform.core.message.QueryReqBean;
import com.jy.platform.restservice.exception.AbaboonException;
import com.jy.platform.restservice.web.base.BaseController;


/**
 * @classname: TCMmRiskFundController
 * @description: 定义  风险金 控制层
 * @author:  dell
 */
@Controller
@Scope("prototype")
@RequestMapping("/tCMmRiskFund")
public class TCMmRiskFundController extends BaseController{
    private static final Logger logger =  LoggerFactory.getLogger(TCMmRiskFundController.class);

    @Autowired
    @Qualifier("com.jy.modules.cims.component.common.service.TCMmRiskFundService")
    private TCMmRiskFundService service;
    
    @Autowired
    @Qualifier("com.jy.modules.cims.deal.service.DealService")
    private DealService dealService;
    
    @Autowired
    @Qualifier("com.jy.modules.cims.component.sysAssist.CSysAssistImpl")
    private CSysAssistImpl csysAssistimpl;
    
    /**
     * 通过 Controller 请求 跳转 进入至相关 页面
     */
    @RequestMapping(value = "/prepareExecute/{operate}")
    public ModelAndView execute(@PathVariable("operate") String operate) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        
        if("toQueryPage".equals(operate)){//跳转至 查询页面
        	model.setViewName("cims/creditManage/queryTCMmRiskFund");
        }else if("toAdd".equals(operate)){ //跳转至 新增页面
        	model.setViewName("cims/creditManage/addTCMmRiskFund");
        }else if("toUpdate".equals(operate)){//跳转至 修改页面
        	String id = this.getParameterString("id");
        	model = this.queryOneRiskFundDealDto(id);
        	model.setViewName("cims/creditManage/updateTCMmRiskFund");
        }else if("toView".equals(operate)){//跳转至 查看页面
        	String id = this.getParameterString("id");
        	model = this.queryOneRiskFundDealDto(id);
        	model.setViewName("cims/creditManage/viewTCMmRiskFund");
        }
        
        return model;
    }
    
    /**
     * @author dell
     * @description:查询分页列表
     * @date 2015-02-06 16:47:40
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryListTCMmRiskFund")
    @ResponseBody
    public DataMsg queryListTCMmRiskFund(HttpServletRequest request, TCMmRiskFundDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {
        
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		
        List<TCMmRiskFundDTO> list = service.searchTCMmRiskFundByPaging(params.getSearchParams());
        
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
    

    /**
     * @author dell
     * @description:新增
     * @date 2015-02-06 16:47:40
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws
     */
    @RequestMapping(value = "/insertTCMmRiskFund")
    @ResponseBody
    public DataMsg insertTCMmRiskFund(HttpServletRequest request, TCMmRiskFundDTO dto, @ModelAttribute DataMsg dataMsg){
        try {
        	dto = (TCMmRiskFundDTO)super.initDto(dto);

            service.insertTCMmRiskFund(dto);
            
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("新增成功");
            dataMsg.setData(this.makeJSONData(dto.getId()));
        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
        	logger.error("执行方法insertSysResource异常：", e);
        }
        return dataMsg;
    }

    /**
     * @author dell
     * @description:编辑
     * @date 2015-02-06 16:47:40
     * @param request
     * @param dto
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/updateTCMmRiskFund")
    @ResponseBody
    public DataMsg updateTCMmRiskFund(HttpServletRequest request, TCMmRiskFundDTO dto, @ModelAttribute DataMsg dataMsg){
        try {
        	dto = (TCMmRiskFundDTO)super.initDto(dto);
           
            service.updateTCMmRiskFund(dto);
            
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("修改成功");
            dataMsg.setData(this.makeJSONData(dto.getId()));
        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
            logger.error("执行方法updateSysResource异常：", e);
        }
        return dataMsg;
    }

    /**
     * @author dell
     * @description:删除
     * @date 2015-02-06 16:47:40
     * @param request
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/deleteTCMmRiskFund")
    @ResponseBody
    public DataMsg deleteTCMmRiskFund(HttpServletRequest request, @ModelAttribute DataMsg dataMsg){
    	
    	BaseDTO dto = super.initDto(null);
   	 	String ids = (String) this.getParameter("ids");//格式: 1,2,3
   	 	dataMsg = super.initDataMsg(dataMsg);
		try {
			 service.deleteTCMmRiskFundByPrimaryKey(dto,ids);
			 dataMsg.setMsg("删除成功");
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法deleteSysResource异常：", e);

		}
        
        return dataMsg;
    }
    /**
     * @author dell
     * @description:通过主键查询 其明细信息
     * @date 2015-02-06 16:47:40
     * @param id
     * @return
     */
    private ModelAndView queryOneDTO(String id) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        try{
        	TCMmRiskFundDTO dto = service.queryTCMmRiskFundByPrimaryKey(id);
            //将信息放入 model 以便于传至页面 使用
            model.addObject("dto", dto);
        }catch(Exception e){
        	throw new AbaboonException("执行queryOneDTO异常：",e);
        }
        return model;
    }
    
    
    
    /**
     * @author zhuwenbin
     * @description:查询风险金交易分页列表
     * @date 2015-02-05 15:32:52
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/searchTCMmRiskFundDealByPaging")
    @ResponseBody  
    public DataMsg searchTCMmRiskFundDealByPaging(HttpServletRequest request, TCMmRiskFundDealDetailDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {
    	String dealType = this.getParameterString("dealType");
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	dto.setDealType(dealType);
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		
		List<TCMmRiskFundDealDetailDTO> list = service.searchTCMmRiskFundDealDetailByPaging(params.getSearchParams());
        
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
    
    
    
    /**
     * @author zhuwenbin
     * @description:担保金新增交易结算表和合作机构交易流水表信息
     * @date 2015-02-02 14:49:23
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws
     */
    @RequestMapping(value = "/insertRiskFundAdOrgdeal")
    @ResponseBody
    public DataMsg insertRiskFundAdOrgdeal(HttpServletRequest request, TCMmRiskFundDealDetailDTO dto, @ModelAttribute DataMsg dataMsg){
        try {
        	dto = (TCMmRiskFundDealDetailDTO)super.initDto(dto);
        	
        	//获取交易流水号
        	String dealStreamNo = csysAssistimpl.getBizNo(CimsConstant.BIZNO_TYPE_DEAL);
        	//风险金编码
        	String riskFundCode = csysAssistimpl.getBizNo(CimsConstant.BIZNO_TYPE_DEAL);
        	 //组装交易结算流水信息表
        	TCMmDealCostDTO costDto = new TCMmDealCostDTO();
        	costDto.setDealStreamCode(dealStreamNo); 
        	costDto.setRiskFundSum(dto.getRiskFundDetailSum());
        	costDto.setRiskFundCode(riskFundCode);
        	costDto.setCreateTime(new Timestamp(System.currentTimeMillis()));
        	costDto.setCreateBy(dto.getCreateUserNameExt());
        	costDto.setAccountStatus(CimsConstant.SETTLESTATUS_NC);
        	costDto.setDealType(CimsConstant.DEAL_TYPE_RISK_FUND);
            //组装合作机构交易流水表信息
            TCMmCooperorgDealDTO orgdealDto = new TCMmCooperorgDealDTO();
            orgdealDto.setDealCode(dealStreamNo);
            orgdealDto.setContractCode(dto.getContractCode());
            orgdealDto.setAgreementCode(dto.getAgreementCode());
            orgdealDto.setCooperorgCode(dto.getCooperorgCode());
            orgdealDto.setDealDate(new java.util.Date());
            orgdealDto.setCreateBy(dto.getCreateUserNameExt());
            orgdealDto.setCreateTime(new Timestamp(System.currentTimeMillis()));
            //组装担保金表信息
            TCMmRiskFundDTO riskFundDTO = new TCMmRiskFundDTO();
           
            riskFundDTO.setRiskFundCode(riskFundCode);
            riskFundDTO.setRiskFundDetailSum(dto.getRiskFundDetailSum());
            riskFundDTO.setCreateBy(dto.getCreateUserNameExt());
            riskFundDTO.setCreateTime(new Timestamp(System.currentTimeMillis()));
            
            service.insertRiskFundAdOrgdeal(costDto,orgdealDto,riskFundDTO);
            
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("新增成功");
            dataMsg.setData(this.makeJSONData(costDto.getId()));
        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
        	logger.error("执行方法insertRiskFundAdOrgdeal异常：", e);
        }
        return dataMsg;
    }
    
    
    /**
     * @author zhuwenbin
     * @description:通过主键查询 其明细信息
     * @date 2015-02-09 16:47:40
     * @param id
     * @return
     */
    private ModelAndView queryOneRiskFundDealDto(String id) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        try{
        	
        	TCMmRiskFundDealDetailDTO dto = service.queryTCMmRiskFundDealByPrimaryKey(Long.parseLong(id));
            //将信息放入 model 以便于传至页面 使用
            model.addObject("dto", dto);
        }catch(Exception e){
        	throw new AbaboonException("执行queryOneRiskFundDealDto异常：",e);
        }
        return model;
    }
}
